#include "user_database.h"

void UserDatabase::initUserTable()
{
    QSqlQuery query;

    // 创建用户表
    QString createTableSql =
        "CREATE TABLE IF NOT EXISTS users ("
        "id INTEGER PRIMARY KEY AUTOINCREMENT, "
        "username TEXT UNIQUE NOT NULL, "        // 用户名（唯一）
        "password_hash TEXT NOT NULL, "          // 密码哈希值
        "role TEXT NOT NULL DEFAULT 'user', "    // 用户角色
        "status TEXT NOT NULL DEFAULT '启用', "  // 状态：启用/禁用
        "create_time TEXT NOT NULL, "            // 创建时间
        "last_login_time TEXT "                  // 最后登录时间
        ")";

    // 创建索引
    QString createIndexSql =
        "CREATE INDEX IF NOT EXISTS idx_users_username "
        "ON users (username)";

    if (!query.exec(createTableSql) || !query.exec(createIndexSql)) {
        qWarning() << "用户表初始化失败：" << query.lastError().text();
        return;
    }

    // 检查是否已有管理员用户，如果没有则创建默认管理员
    query.prepare("SELECT COUNT(*) FROM users WHERE role = 'admin'");
    if (query.exec() && query.next() && query.value(0).toInt() == 0) {
        // 创建默认管理员账户
        UserInfo adminUser("admin", "admin", "admin");
        if (addUser(adminUser)) {
            qDebug() << "已创建默认管理员账户: admin/admin";
        }

        // 创建默认普通用户
        UserInfo normalUser("user", "user", "user");
        if (addUser(normalUser)) {
            qDebug() << "已创建默认用户账户: user/user";
        }
    }
}

UserInfo UserDatabase::validateUser(const QString &username, const QString &password)
{
    UserInfo userInfo;
    QSqlQuery query;

    query.prepare("SELECT * FROM users WHERE username = ? AND status = '启用'");
    query.bindValue(0, username);

    if (query.exec() && query.next()) {
        userInfo = queryToUserInfo(query);
        if (!userInfo.verifyPassword(password)) {
            userInfo = UserInfo();  // 密码错误，返回空用户
        } else {
            // 更新最后登录时间
            updateLastLoginTime(username);
        }
    }

    return userInfo;
}

bool UserDatabase::addUser(const UserInfo &userInfo)
{
    if (userExists(userInfo.username)) {
        qWarning() << "用户已存在：" << userInfo.username;
        return false;
    }

    QSqlQuery query;
    query.prepare(
        "INSERT INTO users (username, password_hash, role, status, create_time) "
        "VALUES (?, ?, ?, ?, ?)");

    query.bindValue(0, userInfo.username);
    query.bindValue(1, userInfo.passwordHash);
    query.bindValue(2, userInfo.role);
    query.bindValue(3, userInfo.status);
    query.bindValue(4, userInfo.createTime.toString("yyyy-MM-dd hh:mm:ss"));

    if (!query.exec()) {
        qWarning() << "添加用户失败：" << query.lastError().text();
        return false;
    }

    return true;
}

bool UserDatabase::updateUser(const UserInfo &userInfo)
{
    QSqlQuery query;

    // 如果密码哈希为空，则不更新密码
    if (userInfo.passwordHash.isEmpty()) {
        query.prepare("UPDATE users SET role = ?, status = ? WHERE username = ?");
        query.bindValue(0, userInfo.role);
        query.bindValue(1, userInfo.status);
        query.bindValue(2, userInfo.username);
    } else {
        query.prepare(
            "UPDATE users SET password_hash = ?, role = ?, status = ? WHERE username = ?");
        query.bindValue(0, userInfo.passwordHash);
        query.bindValue(1, userInfo.role);
        query.bindValue(2, userInfo.status);
        query.bindValue(3, userInfo.username);
    }

    if (!query.exec()) {
        qWarning() << "更新用户失败：" << query.lastError().text();
        return false;
    }

    return query.numRowsAffected() > 0;
}

bool UserDatabase::deleteUser(const QString &username)
{
    // 不允许删除admin用户（如果它是最后一个管理员）
    QSqlQuery checkQuery;
    checkQuery.prepare("SELECT COUNT(*) FROM users WHERE role = 'admin' AND username != ?");
    checkQuery.bindValue(0, username);

    if (checkQuery.exec() && checkQuery.next()) {
        int adminCount = checkQuery.value(0).toInt();
        if (adminCount == 0 && isAdmin(username)) {
            qWarning() << "无法删除最后一个管理员用户";
            return false;
        }
    }

    QSqlQuery query;
    query.prepare("DELETE FROM users WHERE username = ?");
    query.bindValue(0, username);

    if (!query.exec()) {
        qWarning() << "删除用户失败：" << query.lastError().text();
        return false;
    }

    return query.numRowsAffected() > 0;
}

bool UserDatabase::resetPassword(const QString &username, const QString &newPassword)
{
    QString passwordHash = hashPassword(newPassword);

    QSqlQuery query;
    query.prepare("UPDATE users SET password_hash = ? WHERE username = ?");
    query.bindValue(0, passwordHash);
    query.bindValue(1, username);

    if (!query.exec()) {
        qWarning() << "重置密码失败：" << query.lastError().text();
        return false;
    }

    return query.numRowsAffected() > 0;
}

bool UserDatabase::updateUserStatus(const QString &username, const QString &status)
{
    QSqlQuery query;
    query.prepare("UPDATE users SET status = ? WHERE username = ?");
    query.bindValue(0, status);
    query.bindValue(1, username);

    if (!query.exec()) {
        qWarning() << "更新用户状态失败：" << query.lastError().text();
        return false;
    }

    return query.numRowsAffected() > 0;
}

bool UserDatabase::updateLastLoginTime(const QString &username)
{
    QSqlQuery query;
    query.prepare("UPDATE users SET last_login_time = ? WHERE username = ?");
    query.bindValue(0, QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss"));
    query.bindValue(1, username);

    return query.exec();
}

UserInfo UserDatabase::getUserByUsername(const QString &username)
{
    UserInfo userInfo;
    QSqlQuery query;

    query.prepare("SELECT * FROM users WHERE username = ?");
    query.bindValue(0, username);

    if (query.exec() && query.next()) {
        userInfo = queryToUserInfo(query);
    }

    return userInfo;
}

QVector<UserInfo> UserDatabase::getAllUsers()
{
    QVector<UserInfo> users;
    QSqlQuery query;

    query.prepare("SELECT * FROM users ORDER BY create_time DESC");

    if (query.exec()) {
        while (query.next()) {
            users.append(queryToUserInfo(query));
        }
    } else {
        qWarning() << "获取用户列表失败：" << query.lastError().text();
    }

    return users;
}

bool UserDatabase::userExists(const QString &username)
{
    QSqlQuery query;
    query.prepare("SELECT COUNT(*) FROM users WHERE username = ?");
    query.bindValue(0, username);

    if (query.exec() && query.next()) {
        return query.value(0).toInt() > 0;
    }

    return false;
}

bool UserDatabase::isAdmin(const QString &username)
{
    QSqlQuery query;
    query.prepare("SELECT role FROM users WHERE username = ?");
    query.bindValue(0, username);

    if (query.exec() && query.next()) {
        return query.value("role").toString() == "admin";
    }

    return false;
}

int UserDatabase::getUserCount()
{
    QSqlQuery query;
    query.prepare("SELECT COUNT(*) FROM users");

    if (query.exec() && query.next()) {
        return query.value(0).toInt();
    }

    return 0;
}

QString UserDatabase::hashPassword(const QString &password)
{
    return QString(QCryptographicHash::hash(password.toUtf8(), QCryptographicHash::Md5).toHex());
}

UserInfo UserDatabase::queryToUserInfo(const QSqlQuery &query)
{
    UserInfo userInfo;
    userInfo.id = query.value("id").toInt();
    userInfo.username = query.value("username").toString();
    userInfo.passwordHash = query.value("password_hash").toString();
    userInfo.role = query.value("role").toString();
    userInfo.status = query.value("status").toString();
    userInfo.createTime =
        QDateTime::fromString(query.value("create_time").toString(), "yyyy-MM-dd hh:mm:ss");

    QString lastLoginStr = query.value("last_login_time").toString();
    if (!lastLoginStr.isEmpty()) {
        userInfo.lastLoginTime = QDateTime::fromString(lastLoginStr, "yyyy-MM-dd hh:mm:ss");
    }

    return userInfo;
}

QString UserDatabase::getLastLoginUsername()
{
    QSqlQuery query;
    query.prepare(
        "SELECT username FROM users WHERE last_login_time IS NOT NULL "
        "ORDER BY last_login_time DESC LIMIT 1");

    if (query.exec() && query.next()) {
        return query.value("username").toString();
    }

    return "";  // 如果没有登录记录，返回空字符串
}